package org.jeecg.cn.edu.scau.vm.container.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.jeecg.cn.edu.scau.vm.container.domain.VmContainer;
import org.jeecg.cn.edu.scau.vm.container.domain.VmContainerOperType;
import org.jeecg.cn.edu.scau.vm.container.service.VmContainerBizService;
import org.jeecg.cn.edu.scau.vm.container.vo.DelayContainerVo;
import org.jeecg.cn.edu.scau.vm.container.vo.VmContainerListVo;
import org.jeecg.cn.edu.scau.vm.container.vo.VmContainerVo;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RequestMapping("/vm/vmContainer")
@RestController
public class ContainerController {
    @Resource
    private VmContainerBizService vmContainerBizService;

    private static final Logger logger = LoggerFactory.getLogger(ContainerController.class);

    public static String NO_NAME_CONTAINER = "匿名容器";

    /**
     * 创建容器
     *
     * @param vmContainerVo 容器数据实例
     * @return 下发创建任务
     */
    @PostMapping("/add")
    public Result<String> createContainer(@RequestBody VmContainerVo vmContainerVo) {
        logger.info("创建容器,接收到前端的参数为:{}", vmContainerVo);
        // 校验必传参数
        if (Objects.isNull(vmContainerVo)) {
            return Result.error("传递参数有误!参数对象为空");
        }
        // 1. 选择镜像
        if (Objects.isNull(vmContainerVo.getImageId())) {
            return Result.error("必须选择基础镜像后才能执行容器创建");
        }
        // 2. 指定容器需要使用的机时
        if (Objects.isNull(vmContainerVo.getMachineTime()) || vmContainerVo.getMachineTime() <= 0) {
            return Result.error("请指定容器需要使用的机时");
        }
        // 3. 指定GPU数量
        if (Objects.isNull(vmContainerVo.getGpuCardNumber()) || vmContainerVo.getGpuCardNumber() < 0) {
            return Result.error("请指定容器需要使用的GPU卡的数量");
        }
        // 3. 如果容器没有指定名称,那么默认为匿名容器
        if (Objects.isNull(vmContainerVo.getName()) || vmContainerVo.getName().isEmpty()) {
            vmContainerVo.setName(NO_NAME_CONTAINER);
        }
        return vmContainerBizService.createContainer(vmContainerVo);
    }


    @PostMapping("/createSpecialSchedule")
    public Result<String> createSpecialSchedule(@RequestBody VmContainerVo vmContainerVo) {
        logger.info("提交特殊审核配置,{}", vmContainerVo);
        return vmContainerBizService.createSpecialSchedule(vmContainerVo);
    }

    /**
     * 停用容器
     *
     * @param containerId 容器ID
     * @return 提示语
     */
    @GetMapping("/stopContainer")
    public Result<String> stopContainer(
            @RequestParam(name = "containerId") String containerId) {
        if (Objects.isNull(containerId)) {
            return Result.error("没有选择容器!");
        }
        logger.info("停用容器请求,容器ID为:{}", containerId);
        return vmContainerBizService.stopContainer(containerId);
    }

    /**
     * 启用容器
     *
     * @param containerId 容器ID
     * @return 提示语
     */
    @GetMapping("/startContainer")
    public Result<String> startContainer(
            @RequestParam(name = "containerId") String containerId) {
        if (Objects.isNull(containerId)) {
            return Result.error("没有选择容器!");
        }
        logger.info("启用容器请求,容器ID为:{}", containerId);
        return vmContainerBizService.startContainer(containerId);
    }

    /**
     * 删除容器
     *
     * @param containerId 容器ID
     * @return 提示语
     */
    @DeleteMapping(value = "/delete")
    public Result<String> removeContainer(
            @RequestParam(name = "containerId") String containerId) {
        if (Objects.isNull(containerId)) {
            return Result.error("容器ID不得为空!");
        }
        return vmContainerBizService.removeContainer(containerId);
    }

    /**
     * 延长容器使用时间
     *
     * @param delayContainerVo 延长使用相关信息
     * @return 返回相关提示语
     */
    @PutMapping(value = "/delay")
    public Result<String> delayContainer(@RequestBody DelayContainerVo delayContainerVo) {
        return null;
    }


    /**
     * 分页列表查询,包含有容器对应的节点和镜像数据
     *
     * @param vmContainer 容器查询参数
     * @param pageNo      查询页码
     * @param pageSize    查询页大小
     * @param req         请求体
     * @return 返回数据
     */
    @ApiOperation(value = "vm_container-分页列表查询", notes = "vm_container-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<VmContainerListVo>> queryPageList(VmContainer vmContainer,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<VmContainer> queryWrapper = QueryGenerator.initQueryWrapper(vmContainer, req.getParameterMap());
        Page<VmContainer> page = new Page<>(pageNo, pageSize);
        IPage<VmContainerListVo> pageList = vmContainerBizService.pageContainerDetail(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "vm_container-个人列表查询", notes = "vm_container-个人列表查询")
    @GetMapping(value = "/listMy")
    public Result<IPage<VmContainerListVo>> queryPageListMy(VmContainer vmContainer,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<VmContainer> queryWrapper = QueryGenerator.initQueryWrapper(vmContainer, req.getParameterMap());
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("create_by", loginUser.getId());
        Page<VmContainer> page = new Page<>(pageNo, pageSize);
        IPage<VmContainerListVo> pageList = vmContainerBizService.pageContainerDetail(page, queryWrapper);
        return Result.OK(pageList);
    }

    @ApiOperation(value = "vm_container-获取容器状态枚举", notes = "vm_container-获取容器状态枚举")
    @GetMapping(value = "/getContainerStatusEnum")
    public Result<Map<Integer, String>> getContainerStatusEnum() {
        return vmContainerBizService.getContainerStatusEnum();
    }


    /**
     * 编辑容器相关信息
     *
     * @param vmContainer 容器基础信息
     * @return 返回提示语
     */
    @AutoLog(value = "vm_container-编辑")
    @ApiOperation(value = "vm_container-编辑", notes = "vm_container-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody VmContainer vmContainer) {
        vmContainerBizService.updateById(vmContainer);
        return Result.OK("编辑成功!");
    }


    /**
     * 批量删除
     *
     * @param ids id集合
     * @return 返回提示语
     */
    @AutoLog(value = "vm_container-批量删除")
    @ApiOperation(value = "vm_container-批量删除", notes = "vm_container-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.vmContainerBizService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }


    @AutoLog(value = "vm_container-获取操作类型")
    @ApiOperation(value = "vm_container-获取操作类型", notes = "vm_container-获取操作类型")
    @GetMapping(value = "/getOperationType/{id}")
    public Result<List<VmContainerOperType>> getOperationType(@PathVariable("id") String id) {
        logger.info("读取到的id值为:{}", id);
        return Result.OK(this.vmContainerBizService.getOperationType(id));
    }


}
